<!DOCTYPE html>
<!--
Copyright 2017 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/elements/base-style.html">
<link rel="import" href="/elements/job-page/change-info.html">

<dom-module id="job-details">
  <template>
    <style include="base-style">
      ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
      }

      dt {
        margin-top: 12px;
      }

      dd {
        color: var(--paper-grey-500);
        margin: 0;
        word-break: break-all;
      }

      .section {
        margin: 24px 0;
      }
    </style>

    <ul>
      <template is="dom-if" if="[[getCABELink(user, job)]]">
        <li>
          <a href="https://colab.corp.google.com/google_src/files/head/depot/google3/chrome/engprod/perf/pinpoint/cabe-pinpoint-tryjob-results.ipynb#templateParams=%7B%22pinpoint_job_id%22%3A%22[[job.job_id]]%22%7D&sandboxMode=true" target="_blank">
            CABE's analysis, including Cls
          </a>
      </template>
      <template is="dom-if" if="[[job.bug_id]]">
        <li>
          <a href="[[getJobIssueLink(job)]]" target="_blank">
            [[getJobIssueText(job)]]
          </a>
      </template>
      <li>
        <a href="[[job.results_url]]" target="_blank">
          Analyze benchmark results
        </a>
    </ul>

    <div class="section">
      <h2>Arguments</h2>
      <dl>
        <template is="dom-repeat" items="[[getArguments(job)]]">
          <dt>[[item.key]]
          <template is="dom-if" if="[[item.url]]" restamp>
              <dd><a href="[[item.url]]" target="_blank">[[item.value]]</a>
          </template>
          <template is="dom-if" if="[[!item.url]]" restamp>
              <dd>[[item.value]]
          </template>
        </template>
      </dl>
    </div>

    <div class="section">
      <h2>Repro via command line</h2>
      <dl>
        <template is="dom-repeat" items="[[getReproCmd(job)]]">
          <dd>[[item]]
        </template>
      </div>
    </div>
  </template>

  <script>
    'use strict';

    const PROJECT_GIT_COMMIT_URLS = {
      __proto__: null,
      'chromium': 'https://chromium.googlesource.com/chromium/src/+',
      'v8': 'https://chromium.googlesource.com/v8/v8/+',
    };

    Polymer({
      is: 'job-details',

      properties: {
        job: {
          type: Object,
        },
      },

      isTryJob(job) {
        if (!job) {
          return false;
        }
        return !job.comparison_mode || job.comparison_mode === 'try';
      },

      getJobIssueLink(job) {
        let link = ''
        if (!job || !job.arguments || !job.arguments.bug_id) {
          return link;
        }
        let bug_id = parseInt(job.arguments.bug_id);
        if (bug_id > 2000000) {
          link='https://b.corp.google.com/issues/'+bug_id;
        }
        else {
          let project = this.getProject(job);
          link='https://crbug.com/'+project+'/'+bug_id;
        }
        return link
      },

      getJobIssueText(job) {
        let text = ''
        if (!job || !job.arguments || !job.arguments.bug_id) {
          return text;
        }
        let bug_id = parseInt(job.arguments.bug_id);
        if (bug_id > 2000000) {
          text='Issue '+bug_id;
        }
        else {
          let project = this.getProject(job);
          text='Issue '+project+':'+bug_id;
        }
        return text;
      },

      getCABELink(user, job) {
        return user.endsWith("@google.com") && this.isTryJob(job);
      },

      getProject(job) {
        if (!job || !job.arguments || !job.arguments.project) {
          return 'chromium';
        }
        return job.arguments.project;
      },

      getArguments(job) {
        if (!job) {
          return [];
        }
        const ignoredKeys = ['bug_id', 'name', 'user'];
        const commitKeys = ['base_git_hash', 'end_git_hash', 'start_git_hash'];
        const tuples = [];
        for (const key in job.arguments) {
          const value = job.arguments[key];
          if (ignoredKeys.includes(key)) {
            continue;
          }
          const item = {key, value};
          if (commitKeys.includes(key)) {
            item.key = key+'/commit_position';
          }
          const maybeUrl = this.getArgumentsURL(job, key, value);
          if (maybeUrl) {
              item.url = maybeUrl;
          }
          tuples.push(item);
        }
        tuples.sort(function(a, b) {
          if (a.key < b.key) return -1;
          if (a.key > b.key) return 1;
          return 0;
        });
        return tuples;
      },

      getArgumentsURL(job, key, value) {
        if (value.startsWith("http")) {
          return value
        }
        if (["benchmark", "chart", "story"].includes(key)) {
          const perfCodeSearchURL = new URL("https://source.chromium.org/search")
          perfCodeSearchURL.searchParams.set("q", `${value} language:python (path:tools/perf OR path:third_party/crossbench) -path:third_party/angle`)
          return perfCodeSearchURL.toString();
        }
        if (key.includes("_git_hash")) {
          const maybeCommitURL = PROJECT_GIT_COMMIT_URLS[job.arguments.project];
          if (maybeCommitURL) {
            return `${maybeCommitURL}/${value}`;
          }
        }
        return undefined;
      },

      getReproCmd(job) {
        if (!job) {
          return [];
        }
        if (!this.isTryJob(job)) {
          return ['Bisect jobs are not supported at this time!'];
        }
        let argsList = ['pinpoint experiment-telemetry-start \\'];
        const notesList = [];
        for (const [key, value] of Object.entries(job.arguments)) {
          if (value.trim().length === 0) {
            continue;
          }
          switch (key){
            case 'base_git_hash':
            case 'start_git_hash':
            case 'start_commit':
              argsList.push(`-base-commit=${value} \\`);
              break;
            case 'base_patch':
              argsList.push(`-base-patch-url=${value} \\`);
              break;
            case 'end_git_hash':
            case 'end_commit':
              argsList.push(`-exp-commit=${value} \\`);
              break;
            case 'experiment_patch':
              argsList.push(`-exp-patch-url=${value} \\`);
              break;
            case 'benchmark':
              argsList.push(`-benchmark=${value} \\`);
              break;
            case 'story':
            case 'story_filter':
              argsList.push(`-story=${value} \\`);
              break;
            case 'tags':
            case 'story_tags':
              argsList.push(`-story-tags=${value} \\`);
              break;
            case 'initial_attempt_count':
              argsList.push(`-attempts=${value} \\`);
              break;
            case 'configuration':
              argsList.push(`-cfg=${value} \\`);
              break;
            case 'base_extra_args':
            case 'experiment_extra_args':
            case 'test_extra_args':
            case 'batch_id':
            case 'project':
              if (key === 'project' && value === 'chromium') {
                // The default project is Chromium.
                continue;
              }
              notesList.push(`${key} argument is not supported at this time!`);
              break;
          }
        }
        let idx = argsList.length - 1;
        argsList[idx] = argsList[idx].replace(' \\', '');
        if (notesList.length > 0) {
          argsList = argsList.concat('*** Notes:', notesList);
        }
        return argsList;
      }
    });
  </script>
</dom-module>
